package com.jhj.provider.user.controller;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.jhj.provider.user.po.b.model.UserOpenid;
import com.jhj.provider.user.po.b.model.UserSmsToken;
import com.jhj.provider.user.po.b.model.Users;
import com.jhj.provider.user.service.UserOpenidService;
import com.jhj.provider.user.service.UserService;
import com.jhj.provider.user.service.UserSmsTokenService;
import com.jhj.provider.user.utils.Constants;
import com.jhj.utils.AppResultData;
import com.jhj.utils.HttpClientUtil;
import com.jhj.utils.TimeStampUtil;


@RestController
public class LoginController {
	
	@Autowired
	private UserSmsTokenService userSmsTokenService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserOpenidService userOpenidService;
	
	/**
	 * 获取微信openid
	 * @param request
	 * @param code
	 * 
	 * */
	@RequestMapping("/api/user/getWxOpenidAndSessionKey.json")
	public AppResultData<Object> getWxOpenidAndSessionKey(
			HttpServletRequest request,
			@RequestParam("code") String code){
		
		AppResultData<Object> data = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		
		Map<String,String> params = new HashMap<>();
		params.put("appid", "wx2b2a7241d84bc4c5");
		params.put("secret", "f07928818b4b917891989aa43ece1c08");
		params.put("js_code", code);
		params.put("grant_type", "authorization_code");
		String string = HttpClientUtil.get(url, params);
		
		Gson gson = new Gson();
		Map<String,String> fromJson = gson.fromJson(string, Map.class);
		
		data.setData(fromJson);
		return data;
	}
	
	/**
	 * 登录
	 * @param mobile 手机号
	 * @param sms_token 验证码
	 * @param user_type 用户类型  0 = 普通用户 1= 代理商'
	 * @param user_name 用户名
	 * @param code 微信code
	 * 
	 * @return map：userId，mobile，userName，openid
	 * 
	 * */
	@RequestMapping(value = "/api/user/login.json", method = RequestMethod.POST)
	public AppResultData<Object> login(
			HttpServletRequest request, 
			@RequestParam("mobile") String mobile, 
			@RequestParam("sms_token") String sms_token,
			@RequestParam(value = "user_type", required = false, defaultValue = "0") int userType,
			@RequestParam(value = "user_name", required = false, defaultValue = "") String userName,
			@RequestParam("code") String wxcode){

		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", new String());

		// 1、根据手机后查询 user_sms_token 最新一条记录
		UserSmsToken smsToken = userSmsTokenService.selectByMobileAndType(mobile, userType);

		// 验证码不存在，或者添加时间不存在，返回验证码错误
		if (smsToken == null || smsToken.getAddTime() == null) {
			result = new AppResultData<Object>(Constants.ERROR_999, "", "");
			return result;
		}
		if(!sms_token.equals(smsToken.getSmsToken())) {
			result = new AppResultData<Object>(Constants.ERROR_999, "验证码错误", "");
			return result;
		}
		
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		Map<String,String> params = new HashMap<>();
		params.put("appid", "wx2b2a7241d84bc4c5");
		params.put("secret", "f07928818b4b917891989aa43ece1c08");
		params.put("js_code", wxcode);
		params.put("grant_type", "authorization_code");
		String string = HttpClientUtil.get(url, params);
		
		Gson gson = new Gson();
		Map<String,String> fromJson = gson.fromJson(string, Map.class);

		Map<String,String> map = new HashMap<>();
		// 2、判断是否表记录字段add_time 是否超过30分钟.
		long expTime = TimeStampUtil.compareTimeStr(smsToken.getAddTime().longValue(), System.currentTimeMillis() / 1000);
		// 如果验证码超时，返回超时错误
		if (expTime > 1800) {
			result = new AppResultData<Object>(Constants.ERROR_999, "验证码已失效", "");
			return result;
		} else {
			Users user = new Users();
			user.setMobile(mobile);
			Users u = userService.selectOne(user);
			if(u==null) {
				user.setUserType(userType);
				user.setOpenid(fromJson.get("openid"));
				user.setThirdType("微信");
				user.setName(userName);
				userService.insert(user);
				map.put("userId", String.valueOf(user.getId()));
				
				UserOpenid userOpenid = new UserOpenid();
				userOpenid.setMobile(mobile);
				userOpenid.setUserType(0);
				userOpenid.setOpenid(fromJson.get("openid"));
				userOpenid.setAddTime(TimeStampUtil.getNowSecond().intValue());
				userOpenid.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
				userOpenidService.insert(userOpenid);
			}else {
				map.put("userId", String.valueOf(u.getId()));
			}
		}
		
		map.put("mobile", mobile);
		map.put("userName", userName);
		map.put("openid", fromJson.get("openid"));
		
		result.setData(map);
		return result;
	}
	
}
